import router from "@/router";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { Route } from 'vue-router';
import { token } from '@/utils/storage';
import i18n from '@/lang';
import store from '@/store/index';

NProgress.configure({ showSpinner: false });

const whiteList = ["/login"];

const getPageTitle = (key: string) => {
  const hasKey = i18n.te(key);
  if (hasKey) {
    const pageName = i18n.t(key);
    return `${pageName} - ${process.env.VUE_APP_TITLE}`;
  }
  return process.env.VUE_APP_TITLE;
};

router.beforeEach(async(to: Route, _: Route, next: any) => {
  NProgress.start();

  if (!token.get()) {
    if (whiteList.indexOf(to.path) !== -1) {
      // In the free login whitelist, go directly
      if (to.name === "ModelingLow3d") {
        store.dispatch("closeSideBar", {
          withoutAnimation: false
        });
      } else {
        store.dispatch("openSideBar", {
          withoutAnimation: false
        });
      }
      next();
    } else {
      // Other pages that do not have permission to access are redirected to the login page.
      next(`/login`);
    }
  } else {
    if (to.path === "/login") {
      next({ path: "/" });
    } else {
      if (to.name === "ModelingLow3d") {
        store.dispatch("closeSideBar", {
          withoutAnimation: false
        });
      } else {
        store.dispatch("openSideBar", {
          withoutAnimation: false
        });
      }
      next();
    }
  }
});

router.afterEach((to: Route) => {
  // Finish progress bar
  NProgress.done();

  // set page title
  document.title = getPageTitle(to.meta.title);
});
